﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace FilesAutoPicker
{
    /// <summary>
    /// 文件 选择器：
    ///     用于在很多文件的目录中，找到想要的文件们并拷贝出来，而无需手动找到、拷贝。
    /// </summary>
    class FilesPicker
    {
        /// <summary>
        /// 即将选取的文件列表
        /// </summary>
        static List<string> g_listFilesToPick = new List<string>();

        /// <summary>
        /// 读入的配置文件
        /// </summary>
        const string settingFileName = "filesSet.ini";

        /// <summary>
        /// 根据程序路径进行初始化：获得设置文件下的待处理的文件列表
        /// </summary>
        internal static bool Init(string startupPath)
        {
            string filePath = startupPath+"/"+ settingFileName;
            bool isSuc = false;
            if (File.Exists(filePath))
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    string line;
                    while (reader.EndOfStream == false)
                    {
                        line = reader.ReadLine().Trim();

                        //空行或者注释行跳过：
                        if (line.Equals("") || line.StartsWith("#") 
                        //或者line重复的情况下，跳过
                            || g_listFilesToPick.Contains(line))
                        {
                            continue;
                        }

                        //添加到文件列表中：
                        g_listFilesToPick.Add(line);

                        isSuc = true;
                    }
                }
            }
            else
            {
                string[] toSettingFile = new string[] { 
                    "#请在此文件中填写需要pick的文件（每行一个文件）",
                    "#注释示例：",
                    "#以下为默认创建的列表：",
                    "HELLO.txt",
                };
                File.WriteAllLines(filePath, toSettingFile);
            }

            return isSuc;
        }

        /// <summary>
        /// 挑选文件：将文件从源目录搬运到目标目录中，并记录失败的文件
        /// </summary>
        internal static bool DoPickFiles(string srcFolder, string outputFolder,bool convertToUnix,bool trimEmptyLine, out string failMsg)
        {
            StringBuilder failStrs = new StringBuilder();

            bool allSuc = true;

            for(int i = 0 ; i< g_listFilesToPick.Count ; i++)
            {
                //--获得文件名：
                string srcFileName = srcFolder + "\\" + g_listFilesToPick[i];

                if (File.Exists(srcFileName))
                {

                    //copy it
                    #region copy file to destination
  
                    string destFileName = outputFolder + "\\" + g_listFilesToPick[i];

                    if (File.Exists(destFileName))
                    {
                        File.Delete(destFileName);
                    }



                    if (convertToUnix)
                    {
                        //Read & convert to unix format
                        StreamReader sr = new StreamReader(srcFileName);
                        StreamWriter sw = new StreamWriter(destFileName);
                        sw.NewLine = "\n";
                        
                        string str;
                        while (sr.EndOfStream==false)
                        {
                            str = sr.ReadLine();

                            //--Trim blank line if need.
                            if (trimEmptyLine && str.Trim().Equals(""))
                            {
                                continue;
                            }
                            
                            sw.Write(str);

                            //--Write new line if need.
                            if (sr.EndOfStream == false)
                            {
                                sw.Write('\n');
                            }
                            
                        }

                        sw.Flush();

                        sw.Close();
                        sr.Close();
                    }
                    else
                    {
                        //copy it directly
                        File.Copy(srcFileName, destFileName);
                    }

                    #endregion
                }
                else
                {
                    allSuc = false;

                    //add it to failList
                    failStrs.Append(g_listFilesToPick[i]);
                    failStrs.Append("\n");
                }
            }

            if (allSuc)
            {
                failMsg = null;
            }
            else
            {
                failMsg = failStrs.ToString();
            }

            return allSuc;
        }
    }
}
